﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microhard.WeixinMP.Interfaces;
using Microhard.WeixinMP.Models;
using HtmlAgilityPack;
using System.ServiceModel.Dispatcher;
using System.Text.RegularExpressions;

namespace Microhard.WeixinMP.Impls
{
    public class Web_MessageResultParser : IWeixinMPHtmlParser<List<WXMPMessageWithFakeIDModel>>
    {
        public List<WXMPMessageWithFakeIDModel> ParseObject(string html)
        {
            HtmlDocument doc = new HtmlDocument();
            doc.LoadHtml(html);
            var jsonArr = doc.DocumentNode.SelectSingleNode("//script[contains(text(), 'wx.cgiData')]");
            //使用正则过滤出List
            var m = Regex.Match(jsonArr.InnerText, @"\[\{.*?\}\]");
            string jsonSring = m.Value;
            JsonQueryStringConverter jqsv = new JsonQueryStringConverter();
            var list = (List<WXMPMessageWithFakeIDWXModel>)jqsv.ConvertStringToValue(jsonSring, typeof(List<WXMPMessageWithFakeIDWXModel>));
            return (from l in list
                    select new WXMPMessageWithFakeIDModel
                    {
                        Content = l.content,
                        DateTime = l.date_time,
                        FakeId = l.fakeid,
                        HasReply = l.has_reply,
                        Id = long.Parse(l.id),
                        NickName = l.nick_name,
                        RecordDatetime = DateTime.Now,
                        Type = l.type
                    }).ToList();
        }
    }
}
